#ifndef CTREEMODEL_H
#define CTREEMODEL_H

#include "ctreeitem.h"
#include "cdatabase.h"

#include <QAbstractItemModel>
#include <QMimeData>
#include <QModelIndex>
#include <QVariant>

class CTreeModel : public QAbstractItemModel
{
    Q_OBJECT

    CDatabase &m_db;

    void debug(QString msg) const { qDebug() << "[TreeModel]\t" + msg; }

public:
    CTreeModel(CDatabase &db, QObject *parent = 0);
    ~CTreeModel();

    static QString rootId() { return QString(32, QChar('0')); }

    QVariant data(const QModelIndex &index, int role) const;
    Qt::ItemFlags flags(const QModelIndex &index) const;
    QVariant headerData(int section, Qt::Orientation orientation,
                         int role = Qt::DisplayRole) const;
    QModelIndex index(int row, int column,
                       const QModelIndex &parent = QModelIndex()) const;
    QModelIndex parent(const QModelIndex &index) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;

    QString itemId(const QModelIndex &index) const;
    QString itemName(const QModelIndex &index) const;
    QString itemName(QString) const;

    CTreeItem* item(const QModelIndex &index);

    Qt::DropActions supportedDropActions() const;
    QStringList mimeTypes() const;
    QMimeData* mimeData(const QModelIndexList &indexes) const;
    bool dropMimeData(const QMimeData *data,
     Qt::DropAction action, int row, int column, const QModelIndex &parent);

    QModelIndex findIndex(QModelIndex idx, QString id);

private:
    void setupModelData(CTreeItem *parent);

    CTreeItem *rootItem;

    CTreeItem* createRoot();

public slots:
    void refill(bool need_update=true);
    void update(CTreeItem *item);

    void moveSection(QString id, QString parent);
    void moveEntry(QString id, QString parent);

signals:
    void update(bool);
};

#endif // CTREEMODEL_H
